// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', function() {
    // 初始化所有功能
    initImageUpload();
    initSidebar();
    initDeleteConfirm();
});

// 图片上传功能
function initImageUpload() {
    const imageUploads = document.querySelectorAll('.image-upload');

    imageUploads.forEach(function(upload) {
        const fileInput = document.getElementById(upload.getAttribute('data-input'));
        const preview = document.getElementById(upload.getAttribute('data-preview'));

        upload.addEventListener('click', function() {
            fileInput.click();
        });

        fileInput.addEventListener('change', function() {
            if (this.files && this.files[0]) {
                const reader = new FileReader();

                reader.onload = function(e) {
                    preview.src = e.target.result;
                    preview.style.display = 'block';
                };

                reader.readAsDataURL(this.files[0]);
            }
        });
    });
}

// 侧边栏功能
function initSidebar() {
    const sidebarToggle = document.querySelector('.navbar-toggler');
    const sidebar = document.querySelector('.sidebar');

    if (sidebarToggle && sidebar) {
        sidebarToggle.addEventListener('click', function() {
            sidebar.classList.toggle('show');
        });
    }
}

// 删除确认功能
function initDeleteConfirm() {
    const deleteButtons = document.querySelectorAll('.btn-delete');

    deleteButtons.forEach(function(button) {
        button.addEventListener('click', function(e) {
            if (!confirm('确定要删除这条记录吗？此操作不可恢复。')) {
                e.preventDefault();
            }
        });
    });
}

// 表单验证
function validateForm(formId) {
    const form = document.getElementById(formId);
    const inputs = form.querySelectorAll('input[required], textarea[required], select[required]');
    let isValid = true;

    inputs.forEach(function(input) {
        if (!input.value.trim()) {
            input.classList.add('is-invalid');
            isValid = false;
        } else {
            input.classList.remove('is-invalid');
        }
    });

    return isValid;
}

// 显示通知
function showNotification(message, type) {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
    notification.style.top = '20px';
    notification.style.right = '20px';
    notification.style.zIndex = '9999';
    notification.style.minWidth = '300px';
    notification.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;

    // 添加到DOM
    document.body.appendChild(notification);

    // 3秒后自动移除
    setTimeout(() => {
        notification.classList.remove('show');
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 300);
    }, 3000);
}

// AJAX请求封装
function ajaxRequest(url, method, data, successCallback, errorCallback) {
    const xhr = new XMLHttpRequest();

    xhr.open(method, url, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                try {
                    const response = JSON.parse(xhr.responseText);
                    if (response.success) {
                        successCallback(response);
                    } else {
                        errorCallback(response.message || '操作失败');
                    }
                } catch (e) {
                    errorCallback('服务器响应错误');
                }
            } else {
                errorCallback('请求失败，请重试');
            }
        }
    };

    xhr.send(typeof data === 'string' ? data : Object.keys(data).map(key => `${key}=${encodeURIComponent(data[key])}`).join('&'));
}

// 表格排序功能
function initTableSort() {
    const tableHeaders = document.querySelectorAll('.table-sortable th');

    tableHeaders.forEach(function(header) {
        if (header.classList.contains('no-sort')) return;

        header.style.cursor = 'pointer';
        header.addEventListener('click', function() {
            const table = header.closest('table');
            const tbody = table.querySelector('tbody');
            const rows = Array.from(tbody.querySelectorAll('tr'));
            const columnIndex = Array.from(header.parentNode.children).indexOf(header);
            const isAscending = !header.classList.contains('sort-asc');

            // 移除所有排序类
            tableHeaders.forEach(h => {
                h.classList.remove('sort-asc', 'sort-desc');
            });

            // 添加当前排序类
            header.classList.add(isAscending ? 'sort-asc' : 'sort-desc');

            // 排序行
            rows.sort((a, b) => {
                const aValue = a.children[columnIndex].textContent.trim();
                const bValue = b.children[columnIndex].textContent.trim();

                if (isAscending) {
                    return aValue.localeCompare(bValue, 'zh-CN');
                } else {
                    return bValue.localeCompare(aValue, 'zh-CN');
                }
            });

            // 重新排列行
            rows.forEach(row => tbody.appendChild(row));
        });
    });
}

// 分页功能
function initPagination() {
    const paginationLinks = document.querySelectorAll('.pagination a');

    paginationLinks.forEach(function(link) {
        link.addEventListener('click', function(e) {
            e.preventDefault();

            const url = this.getAttribute('href');
            const container = document.querySelector(this.getAttribute('data-container'));

            // 显示加载状态
            container.innerHTML = `
                <div class="d-flex justify-content-center p-4">
                    <div class="spinner-border" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                </div>
            `;

            // 加载新内容
            ajaxRequest(url, 'GET', null, function(response) {
                container.innerHTML = response.html;
                initPagination(); // 重新初始化分页
                initTableSort(); // 重新初始化表格排序
                initDeleteConfirm(); // 重新初始化删除确认
            }, function(error) {
                container.innerHTML = `<div class="alert alert-danger">${error}</div>`;
            });
        });
    });
}